import { PDSClient } from 'aliyun-pds-js-sdk/browser'

// {
//     "access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIyNDhiOGU4MjNhOTI0YWRkYTQ4MzM5NDkzZjgxNWM3NiIsImN1c3RvbUpzb24iOiJ7XCJjbGllbnRJZFwiOlwiQlhlcDliS0hjMmxBSVNjalwiLFwiZG9tYWluSWRcIjpcImh6MTI5NDRcIixcInNjb3BlXCI6W1wiRFJJVkUuQUxMXCIsXCJTSEFSRS5BTExcIixcIkZJTEUuQUxMXCIsXCJVU0VSLkFMTFwiLFwiU1RPUkFHRS5BTExcIixcIlNUT1JBR0VGSUxFLkxJU1RcIixcIkFDQ09VTlQuQUxMXCIsXCJPQVVUSC5BTExcIixcIkJBVENIXCIsXCJNRU1CRVJTSElQLkFMTFwiLFwiR1JPVVAuQUxMXCIsXCJBVURJVExPRy5BTExcIl0sXCJyb2xlXCI6XCJ1c2VyXCIsXCJyZWZcIjpcIlwiLFwiZGV2aWNlX2lkXCI6XCIxZjQ3YjllMzc5NzY0Y2VhYTA2NWFhZjRjZTQ5MzdjZlwifSIsImV4cCI6MTY5ODE0MjIxNywiaWF0IjoxNjk4MTM0OTU3fQ.a2FYt3oiWAncVdjHDntkQ3OLewvZfSaAjY2RDygLvWmKZj_aSPUtl4jP_AaoJxJ3oQ37omu2NM51zf2guEmln7W57x6iOFkrDxkHfsuDK5WirYc2m9Zev2LW5Fw_NVTC6brDK0YWrCaVQyfH0KNgNHl5ugQF4DVdXHbp8GTdMUA",
//     "refresh_token": "1f47b9e379764ceaa065aaf4ce4937cf",
//     "expires_in": 7200,
//     "token_type": "Bearer",
//     "user_id": "248b8e823a924adda48339493f815c76",
//     "user_name": "13815261984",
//     "avatar": "",
//     "nick_name": "13815261984",
//     "default_drive_id": "1020",
//     "default_sbox_drive_id": "",
//     "role": "user",
//     "status": "enabled",
//     "expire_time": "2023-10-24T10:10:17Z",
//     "state": "",
//     "exist_link": [],
//     "need_link": false,
//     "user_data": {},
//     "pin_setup": false,
//     "is_first_login": false,
//     "need_rp_verify": false,
//     "domain_id": "hz12944"
// }
// const client_id = '4UvB8xDFweNlFuzr'
// const privary_key_pem = 'RK6sNMb8DDRKaKoWLXXQvvHUlWqQbw'
export default class Pds {
  static USERID = 'pds_userid'
  constructor({
    backurl = 'https://premium.learningmall.cn/callback/pdsoauth',
    domain_id = 'hz12944', // 如：bj123 您的domainID
    client_id = 'BXep9bKHc2lAIScj',
    // privary_key_pem = 'a11OvDwk4La1MxVg9yRZeBfvY4QoVJ',
  } = {}) {
    this.events = []
    this.backurl = backurl
    this.domain_id = domain_id
    this.client_id = client_id
    // this.privary_key_pem = privary_key_pem

    this.user_id = this.getLocalStorage(Pds.USERID) || ''

    this.code = new URL(location).searchParams.get('code')
    if (!this.code) {
      location.href = this.codeUrl
    } else {
      this.getAccesToken(this.code)
    }
  }
  onMounted(event) {
    this.events.push(event)
  }
  /**
   * 获取授权TOKEN
   * ?code=cbc6a97230744b9ca4f4584b87f589b0
   */
  async getAccesToken() {
    try {
      let bodyData = this.user_id ? { user_id: this.user_id } : { code: this.code }
      let res = await fetch('http://10.7.2.175/premium/web/alitoken.php', {
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(bodyData),
      })
      if (res.status === 200) {
        let data = await res.json()
        this.init(data)

        const event = this.events.shift()
        if (event) {
          event(data)
        }
      }
      // console.log('res', res)
    } catch (e) {}
  }
  setLocalStorage(key, value) {
    localStorage.setItem(key, value)
  }
  getLocalStorage(key) {
    return localStorage.getItem(key)
  }
  /**
   * 初始化
   * @param {*} param0
   */
  init({ access_token, refresh_token, default_drive_id, user_id } = {}) {
    if (!this.user_id) {
      this.user_id = user_id
      this.setLocalStorage(Pds.USERID, user_id)
    }
    // console.log('init pds', access_token, refresh_token, default_drive_id)
    this.drive_id = default_drive_id
    this.access_token = access_token
    const config = {
      token_info: { access_token, refresh_token },
      api_endpoint: `https://${this.domain_id}.api.aliyunpds.com`, // PDS API 地址，一般构成为：https://{domainId}.api.aliyunpds.com。
    }

    this.client = new PDSClient(config)

    this.client.on('error', (error, req_opt) => {
      console.log('Error', error)
      console.log('Request Options:', req_opt)
    })
    console.log('init pds success')
  }

  /**
   * 是否准备就绪
   */
  get isReady() {
    return !!this.access_token
  }

  /**
   * 获取授权链接
   */
  get codeUrl() {
    const uri = `https://${this.domain_id}.api.aliyunpds.com/v2/oauth/authorize?client_id=${
      this.client_id
    }&redirect_uri=${
      this.backurl
    }&login_type=default&scope=all&response_type=code&state=${encodeURIComponent(location.href)}`
    return uri
  }

  /**
   * 上传文件
   * @param {*} file
   * @param {*} options
   * @returns
   */
  async uploadFile(file, options = {}) {
    let uploadTo = { drive_id: this.drive_id, parent_file_id: 'root' }
    // { file_id, file_key, upload_id, id }
    let res = await this.client.uploadFile(file, uploadTo, options)
    return res
  }

  /**
   * 获取下载链接
   * @param {*} file_id
   * @returns
   */
  async getFileDownloadUrl(file_id = '6537631b3216ec8cf2444f56bed988cf8729e700') {
    const info = await this.client.getFileDownloadUrl({
      drive_id: this.drive_id,
      file_id,
    })
    console.log('getFileDownloadUrl', info)
    return info
  }

  /**
   * 删除文件
   * @param {*} file_id
   * @returns
   */
  async deleteFile(file_id = '') {
    return await this.client.deleteFile({ drive_id: this.drive_id, file_id }, true)
  }

  /**
   * 获取文件列表
   * @returns array[fileitem]
   */
  async getListFiles() {
    const { items = [] } = await this.client.listFiles({
      drive_id: this.drive_id,
      parent_file_id: 'root',
    })
    console.log('getFileList', items)
    return items
  }

  /**
   * 创建一个上传任务
   * @param {*} file
   * @param {*} options {onProgress}
   * @returns
   */
  async createUploadTask(file, options = {}) {
    let cp = {
      file,
      path_type: 'StandardMode', // domain 的 path_type 属性。取值范围：StandardMode。
      drive_id: this.drive_id, // 上传目的地的云盘ID。 drive_id和share_id互斥，只需传一个即可。
      parent_file_id: 'root', // 上传目的地的父目录ID。
    }
    // 创建上传任务
    this.task = this.client.createUploadTask(cp)

    const { onProgress = () => {} } = options
    // 监听进度
    // 任务状态。state 可能值为：computing_hash（计算秒传）, running（正在上传）, checking（计算crc64）
    // 进度，取值范围：0 - 100。
    this.task.on('progress', (state, progress) => {
      console.log('progress===', state, progress)
      onProgress(state, progress)
    })
    // 开始上传
    this.task.start()
    console.log('createUploadTask', this.task)
    return this.task
  }

  /**
   * 创建分享链接
   * @param {*} file_id
   */
  async createShareLink(file_id = '') {
    console.log('创建分享链接开始')
    let res = await this.client.createShareLink({
      description: 'test1',
      drive_id: this.drive_id,
      expiration: '2023-12-08T15:59:59.999Z',
      file_id_list: [file_id],
      share_pwd: '123123',
    })
    console.log('创建分享链接成功', res)
  }

  /**
   * 获取分享链接
   */
  async getShareLink() {
    const share_id = 'PcfRb1kaPut'
    let info = await this.client.getShareLinkByAnonymous({ share_id })
    console.log('getShareLink', info)
  }
}
